package com.example.javabasic.other;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @description 测试用controller
 * @Author Lin FuYuan
 * 文件下载文档地址: https://www.cnblogs.com/xdp-gacl/p/4200090.html
 * @date 2021/6/23
 */
@RestController
@RequestMapping("/other")
public class OtherController {
    @RequestMapping("/download")
    public void downLoadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String filePath = "G:\\jipingg18\\3DMGAME-NFS18.RLD.v1.4.CHT.Green.part1.rar";
        String fileName = "3DMGAME-NFS18.RLD.v1.4.CHT.Green.part1.rar";
        File file = new File(filePath);

        //设置响应头，控制浏览器下载该文件
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        try ( //读取要下载的文件，保存到文件输入流
              FileInputStream in = new FileInputStream(file);
              //创建输出流
              OutputStream out = response.getOutputStream();) {
            //创建缓冲区
            byte[] buffer = new byte[1024];
            int len = 0;
            //循环将输入流中的内容读取到缓冲区当中
            while ((len = in.read(buffer)) > 0) {
                //输出缓冲区的内容到浏览器，实现文件下载
                out.write(buffer, 0, len);
            }
            //关闭文件输入流
            in.close();
            //关闭输出流
            out.close();
        }


    }

}
